import {Component, OnInit, ViewChild} from '@angular/core';
import {Globals} from '../../../globals';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {ApiUrl} from '../../../config/api-url';
import {PageHelper} from '../../../utils/page-helper-model';
import {ActivatedRoute, Router} from '@angular/router';
import {Consts} from '../../../config/consts';
import {UserInfoModel} from '../../../models/user-info.model';
import {RoleIdEnum} from '../../../enums/role-id.enum';
import {UserStatusEnum} from '../../../enums/user-status.enum';
import {MerchantUpdateComponent} from '../merchant-update/merchant-update.component';

@Component({
  selector: 'app-merchant-list',
  templateUrl: './merchant-list.component.html',
  styleUrls: ['./merchant-list.component.less']
})
export class MerchantListComponent implements OnInit {
  merchantUpdateVisible = false;
  @ViewChild('merchantUpdateComponent')
  merchantUpdateComponent: MerchantUpdateComponent;

  isMobile = Globals.isMobile();
  listOfData: any;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  formModel: FormGroup;
  // 机构
  agencyList: [];
  // 运营商
  userList: [];

  // 显示模态框
  isVisible = false;
  // 用户信息
  userInfo: UserInfoModel;
  receiptType: number;
  nzVisible = false;
  userId: number;
  userIdType = 1;
  userName: string;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  userStatus = {
    ENABLED: UserStatusEnum.ENABLED,
    LOCKED: UserStatusEnum.LOCKED
  };
  freezeReason: any;
  isOkLoading = false;

  constructor(private fb: FormBuilder, private baseService: BaseService, private router: Router, private activatedRoute: ActivatedRoute) {
    this.buildForm();
    this.activatedRoute.queryParams.subscribe(params => {
      if (params.userId != null) {
        this.formModel.get('userId').setValue(params.userId);
        this.getAgentsData();
      } else {
        this.getAgentsData();
      }
    });
  }


  ngOnInit(): void {
    this.getAllAgencyOfName();
    this.getAllUserOfName();
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
  }

  showMerchantUpdateModal(data) {
    this.merchantUpdateVisible = true;
    this.merchantUpdateComponent.loadingModal(data);
  }

  settingMerchantUpdate($event: any) {
    this.merchantUpdateVisible = $event;
  }

  buildForm() {
    this.formModel = this.fb.group({
      agencyId: ['', []],
      userId: ['', []],
      keyword: ['', []],
      userIdType: [1, []],
    });
  }


  submitForm() {
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }

  changeUserIdType(e:any){
    this.userIdType = e;
    if(this.userIdType == 1){
      this.getAllUserOfName();
    }else{
      this.getAllUserSubAccountOfName();
    }
    this.getAgentsData();
    // console.log('进入拉吗',e)
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }
  getAgentsData() {
    this.baseService.findListByMuchCondition(ApiUrl.UserUrl + '/list', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
          this.listOfData.forEach(res => {
            res.expand = false;
          })
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserOfName() {
    let agencyId = this.formModel.get('agencyId').value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserSubAccountOfName(){
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserSubAccountOfName?userIdType=' + this.userIdType).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.getAgentsData();
  }

  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }

  skipStore(data: any) {
    this.router.navigateByUrl('/store?userId=' + data.id,
      {skipLocationChange: true});
  }

  skipAgency(data) {
    this.router.navigateByUrl('/agency?agencyNo=' + data.agencyNo,
      {skipLocationChange: true});
  }

  addStore() {
    this.isVisible = true;
  }

  // 子组件向父组件传值
  setVisible(body) {
    this.isVisible = body.isVisible;
    this.getAgentsData();
  }


  clickReceiptType(data) {
    this.receiptType = data.receiptType;
    this.userId = data.id;
    this.nzVisible = true;
  }

  handleCancel() {
    this.nzVisible = false;
  }


  lockUser(user: any, userStatus, msg, tplContent) {
    if (this.userStatus.ENABLED == userStatus) {
      if (user.freezeReason != null) {
        msg = '因' + user.freezeReason + '被冻结，您确定要恢复';
      } else {
        msg = '确定要恢复该账号吗？';
      }
      this.dispose(user.id, userStatus, msg);
    } else {
      msg = '确定要冻结该账号吗？';
      this.baseService.layer.createTplModal('请输入冻结原因', tplContent, confirm => {
        if (confirm) {
          if (this.freezeReason == null || this.freezeReason == '') {
            this.baseService.layer.modalError('请输入冻结原因');
            return;
          }
          this.dispose(user.id, userStatus, msg);
        }
      });
    }
  }

  dispose(userId, userStatus, msg) {
    this.baseService.layer.modalConfirm(msg, confirm2 => {
      if (confirm2) {
        const body = {
          id: userId,
          status: userStatus,
          freezeReason: this.freezeReason,
        };
        this.baseService.put(ApiUrl.UserUrl, body).subscribe(data => {
          if (data.status == 0) {
            this.freezeReason = null;
            this.getAgentsData();
          } else {
            this.baseService.layer.messageError(data.msg);
            this.freezeReason = null;
          }
        });
      }
    });
  }

  resetPassword(data) {
    this.baseService.layer.modalConfirm('确定要重置密码吗？', result => {
      if (result) {
        this.baseService.put(ApiUrl.UserUrl + '/resetPwdById', data).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('重置密码成功！');
              this.getAgentsData();
            } else {
              this.baseService.layer.messageError('重置密码失败：' + data.msg);
            }
          }
        );
      }
    });
  }
  resetOperatePassword(data) {
    this.baseService.layer.modalConfirm('确定要重置操作密码吗？', result => {
      if (result) {
        this.baseService.put(ApiUrl.UserUrl + '/resetOperatePwdById', data).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('重置操作密码成功！新密码为'+ data.data);
              this.getAgentsData();
            } else {
              this.baseService.layer.messageError('重置操作密码失败：' + data.msg);
            }
          }
        );
      }
    });
  }
}
